package com.jeecg.demo.controller;

import com.jeecg.demo.entity.*;
import com.jeecg.demo.service.SysMenuServiceI;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.service.SystemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Title: Controller
 * @Description: 权限管理
 * @author onlineGenerator
 * @date 2018-12-03 09:22:12
 * @version V1.0
 *
 */
@Controller
@RequestMapping("/sysMenuController")
public class SysMenuController extends BaseController {
	private static final Logger logger = LoggerFactory
			.getLogger(SysMenuController.class);

	@Autowired
	private SysMenuServiceI sysMenuService;
	@Autowired
	private SystemService systemService;

	/**
	 * 权限管理列表 页面跳转
	 *
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("com/jeecg/sysMenu/sysMenuList");
	}

	/**
	 * easyui AJAX请求数据
	 *
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(SysMenuEntity sysMenu, HttpServletRequest request,
			HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(SysMenuEntity.class, dataGrid);
		// 查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq,
				sysMenu, request.getParameterMap());
		try {
			// 自定义追加查询条件
			cq.eq("appid", "2");
			cq.add();
		} catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.sysMenuService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除权限管理
	 *
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(SysMenuEntity sysMenu, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		sysMenu = systemService.getEntity(SysMenuEntity.class, sysMenu.getId());
		message = "删除成功";
		try {
			sysMenuService.delete(sysMenu);
			systemService.addLog(message, Globals.Log_Type_DEL,
					Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 批量删除权限管理
	 *
	 * @return
	 */
	@RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "删除成功";
		try {
			for (String id : ids.split(",")) {
				SysMenuEntity sysMenu = systemService.getEntity(
						SysMenuEntity.class, Integer.parseInt(id));
				sysMenuService.delete(sysMenu);
				systemService.addLog(message, Globals.Log_Type_DEL,
						Globals.Log_Leavel_INFO);
			}
		} catch (Exception e) {
			e.printStackTrace();
			message = "删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 添加权限管理
	 *
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(SysMenuEntity sysMenu, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "添加成功";
		try {
			sysMenuService.save(sysMenu);
			systemService.addLog(message, Globals.Log_Type_INSERT,
					Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 更新权限管理
	 *
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(SysMenuEntity sysMenu, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "更新成功";
		SysMenuEntity t = sysMenuService.get(SysMenuEntity.class,
				sysMenu.getId());
		try {
			MyBeanUtils.copyBeanNotNull2Bean(sysMenu, t);
			sysMenuService.saveOrUpdate(t);
			systemService.addLog(message, Globals.Log_Type_UPDATE,
					Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 权限管理新增页面跳转
	 *
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(SysMenuEntity sysMenu, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(sysMenu.getId())) {
			sysMenu = sysMenuService.getEntity(SysMenuEntity.class,
					sysMenu.getId());
			req.setAttribute("sysMenuPage", sysMenu);
		}
		return new ModelAndView("com/jeecg/sysMenu/sysMenu-add");
	}

	/**
	 * 权限管理编辑页面跳转
	 *
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(SysMenuEntity sysMenu, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(sysMenu.getId())) {
			sysMenu = sysMenuService.getEntity(SysMenuEntity.class,
					sysMenu.getId());
			req.setAttribute("sysMenuPage", sysMenu);
		}
		return new ModelAndView("com/jeecg/sysMenu/sysMenu-update");
	}

	/**
	 * 导入功能跳转
	 *
	 * @return
	 */
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		req.setAttribute("controller_name", "sysMenuController");
		return new ModelAndView("common/upload/pub_excel_upload");
	}

	/**
	 * 导出excel
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXls")
	public String exportXls(SysMenuEntity sysMenu, HttpServletRequest request,
			HttpServletResponse response, DataGrid dataGrid, ModelMap modelMap) {
		CriteriaQuery cq = new CriteriaQuery(SysMenuEntity.class, dataGrid);
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq,
				sysMenu, request.getParameterMap());
		List<SysMenuEntity> sysMenus = this.sysMenuService
				.getListByCriteriaQuery(cq, false);
		modelMap.put(NormalExcelConstants.FILE_NAME, "权限管理");
		modelMap.put(NormalExcelConstants.CLASS, SysMenuEntity.class);
		modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("权限管理列表",
				"导出人:" + ResourceUtil.getSessionUser().getRealName(), "导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST, sysMenus);
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}

	/**
	 * 导出excel 使模板
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(SysMenuEntity sysMenu,
			HttpServletRequest request, HttpServletResponse response,
			DataGrid dataGrid, ModelMap modelMap) {
		modelMap.put(NormalExcelConstants.FILE_NAME, "权限管理");
		modelMap.put(NormalExcelConstants.CLASS, SysMenuEntity.class);
		modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("权限管理列表",
				"导出人:" + ResourceUtil.getSessionUser().getRealName(), "导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST, new ArrayList());
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request,
			HttpServletResponse response) {
		AjaxJson j = new AjaxJson();

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<SysMenuEntity> listSysMenuEntitys = ExcelImportUtil
						.importExcel(file.getInputStream(),
								SysMenuEntity.class, params);
				for (SysMenuEntity sysMenu : listSysMenuEntitys) {
					sysMenuService.save(sysMenu);
				}
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return j;
	}

	@RequestMapping(params = "getTreeDemoData", method = { RequestMethod.GET,
			RequestMethod.POST })
	@ResponseBody
	public AjaxJson getTreeDemoData(SysMenuEntity depatr,
			HttpServletResponse response, HttpServletRequest request,Integer appId,
			@RequestParam ("datas") String[] data) {
		AjaxJson j = new AjaxJson();
		try {
			List<SysMenuEntity> depatrList = new ArrayList<SysMenuEntity>();
			String hqlText="";
			if (appId==0) {
				hqlText="from SysMenuEntity t";
			} else {
				hqlText=" from SysMenuEntity t where t.appid = "+appId+" ";
			}
			StringBuffer hql = new StringBuffer(hqlText);
			depatrList = this.systemService.findHql(hql.toString());
			List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
			Map<String, Object> map = null;
			String[] split = {};
			for (int i = 0; i < data.length; i++) {
				split = data[i].split(",");
			}
			for (SysMenuEntity tsdepart : depatrList) {
				map = new HashMap<String, Object>();
				map.put("chkDisabled", false);
				map.put("click", true);
				map.put("id", tsdepart.getMenuid());
				for (int k = 0; k < split.length; k++) {
					if (split[k].equals(tsdepart.getMenuid().toString())) {
						map.put("checked", true);
						break;
					} else {
						map.put("checked", false);
					}
				}
				map.put("name", tsdepart.getMenutitle());
				map.put("struct", "TREE");
				map.put("title", tsdepart.getMenutitle());
				map.put("parentId", tsdepart.getParentid());
				dataList.add(map);
			}
			j.setObj(dataList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return j;
	}


	@RequestMapping(params = "getUser", method = { RequestMethod.GET,
			RequestMethod.POST })
	@ResponseBody
	public AjaxJson getUser(TSDepart depatr, HttpServletResponse response,
			HttpServletRequest request,String searchText) {
		AjaxJson j = new AjaxJson();
		try {
			List<SysUserEntity> depatrList = new ArrayList<SysUserEntity>();
			String hqlText="";
			if (searchText.equals("")) {
				hqlText=" from SysUserEntity t where t.usertype = '3' and t.isvalid = '1' ";
			}else{
				hqlText=" from SysUserEntity t where t.usertype = '3' and t.isvalid = '1' and t.username = '"+searchText+"' ";
			}

			StringBuffer hql = new StringBuffer(hqlText);
			depatrList = this.systemService.findHql(hql.toString());
			List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
			Map<String, Object> map = null;
			for (SysUserEntity tsdepart : depatrList) {
				map = new HashMap<String, Object>();
				map.put("id", tsdepart.getId());
				map.put("name",
						tsdepart.getUsername() + "(" + tsdepart.getLoginname()
								+ ")");
				map.put("nocheck", true);
				map.put("pId", "1");
				map.put("open", false);
				dataList.add(map);
			}
			j.setObj(dataList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return j;
	}


	@RequestMapping(params = "getRole", method = { RequestMethod.GET,
			RequestMethod.POST })
	@ResponseBody
	public AjaxJson getRole(TSDepart depatr, HttpServletResponse response,
			HttpServletRequest request,String searchText) {
		AjaxJson j = new AjaxJson();
		try {
			List<SysRoleEntity> depatrList = new ArrayList<SysRoleEntity>();
			String hqlText="";
			if (searchText.equals("")) {
				hqlText=" from SysRoleEntity t where t.isvalid = '1' ";
			}else{
				hqlText=" from SysRoleEntity t where t.isvalid = '1' and t.rolename = '"+searchText+"' ";
			}
			StringBuffer hql = new StringBuffer(hqlText);
			depatrList = this.systemService.findHql(hql.toString());
			List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
			Map<String, Object> map = null;
			for (SysRoleEntity tsdepart : depatrList) {
				map = new HashMap<String, Object>();
				map.put("id", tsdepart.getId());
				map.put("name", tsdepart.getRolename());
				map.put("nocheck", true);
				map.put("pId", "1");
				map.put("open", false);
				dataList.add(map);
			}
			j.setObj(dataList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return j;
	}

	@RequestMapping(params = "getOrgnization", method = { RequestMethod.GET,
			RequestMethod.POST })
	@ResponseBody
	public AjaxJson getOrgnization(SysOrgnizationEntity depatr,
			HttpServletResponse response, HttpServletRequest request,String searchText) {
		AjaxJson j = new AjaxJson();
		try {
			List<SysOrgnizationEntity> depatrList = new ArrayList<SysOrgnizationEntity>();
			String hqlText="";
			if (searchText.equals("")) {
				hqlText=" from SysOrgnizationEntity t where t.isvalid = '1' ";
			}else{
				hqlText=" from SysOrgnizationEntity t where t.isvalid = '1' and t.orgname = '"+searchText+"' ";
			}
			StringBuffer hql = new StringBuffer(hqlText);
			depatrList = this.systemService.findHql(hql.toString());
			List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
			Map<String, Object> map = null;
			for (SysOrgnizationEntity tsdepart : depatrList) {
				map = new HashMap<String, Object>();
				map.put("chkDisabled", false);
				map.put("click", true);
				map.put("id", tsdepart.getOrgid());
				map.put("name", tsdepart.getOrgname());
				map.put("nocheck", true);
				map.put("struct", "TREE");
				map.put("title", tsdepart.getOrgname());
				map.put("parentId", tsdepart.getParentorgid());
				dataList.add(map);
			}
			j.setObj(dataList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return j;
	}

	@RequestMapping(params = "userToPower", method = { RequestMethod.GET,
			RequestMethod.POST })
	@ResponseBody
	public AjaxJson userToPower(TSDepart depatr, HttpServletResponse response,
			HttpServletRequest request,Integer userId) {
		AjaxJson j = new AjaxJson();
		try {
			List<SysAuthscopeEntity> depatrList = new ArrayList<SysAuthscopeEntity>();
			String hqlText="  from SysAuthscopeEntity t where t.privilegetype = '1' and t.memberid = '"+userId+"' and t.isvalid = '1' ";
			StringBuffer hql = new StringBuffer(hqlText);
			depatrList = this.systemService.findHql(hql.toString());
			List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
			Map<String, Object> map = null;
			for (SysAuthscopeEntity tsdepart : depatrList) {
				map = new HashMap<String, Object>();
				map.put("id", tsdepart.getPrivilegeid());
				map.put("type", tsdepart.getPrivilegetype());
				map.put("pId", "1");
				map.put("open", false);
				dataList.add(map);
			}
			j.setObj(dataList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return j;
	}
	@RequestMapping(params = "savePower", method = { RequestMethod.GET,
			RequestMethod.POST })
	@ResponseBody
	public AjaxJson savePower(SysAuthscopeEntity sysAuthscopeEntity, HttpServletResponse response,
			HttpServletRequest request,
			String appId,
			String privilegeId,
			Integer memberid,
			String authType) {
		AjaxJson j = new AjaxJson();
		String message = null;
		try {
			if (appId!=null&privilegeId!=""&memberid!=null&authType!="") {
				message="保存成功";
				String [] stringArr= privilegeId.split(",");
				List<SysAuthscopeEntity> depatrList = new ArrayList<SysAuthscopeEntity>();
				for (int i = 0; i < stringArr.length; i++) {
					String hqlText="  from SysAuthscopeEntity t where t.privilegetype = '1'  and t.memberid = '"+memberid+"' and t.privilegeid = '"+Integer.parseInt(stringArr[i])+"' ";
					StringBuffer hql = new StringBuffer(hqlText);
					depatrList = this.systemService.findHql(hql.toString());
					if (depatrList.isEmpty()) {
						SysAuthscopeEntity sysAuthscope = new SysAuthscopeEntity();
						sysAuthscope.setAppid(appId);
						sysAuthscope.setIsvalid("1");
						sysAuthscope.setPrivilegeid(Integer.parseInt(stringArr[i]));
						sysAuthscope.setMemberid(memberid);
						sysAuthscope.setAuthtype(authType);
						sysAuthscope.setPrivilegetype("1");
						systemService.save(sysAuthscope);
					}else{
						for (SysAuthscopeEntity sysAuth : depatrList) {
							if (sysAuth.getIsvalid().equals("1")) {
								sysAuth.setIsvalid("0");
							} else {
								sysAuth.setIsvalid("1");
							}
							systemService.updateEntitie(sysAuth);
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			message="保存失败";
		}
		j.setMsg(message);
		return j;
	}

}
